package com.commerce.weather.utils;

import android.content.Context;
import android.content.res.AssetManager;

import com.commerce.weather.Entity.City;
import com.commerce.weather.Entity.Type;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;

public class JsonToType {
    /**
     * 解析本地asset下的wid.json文件
     *
     * @param context     上下文
     * @return {@link Type}
     */
    public Type ToType(Context context){
        try {
            String jsonLocation = AssetJSONFile("wid.json", context);
            return new Gson().fromJson(jsonLocation, Type.class);
        } catch (
                IOException e) {
            e.printStackTrace();
        }
         return null;
    }

    /**
     * 解析本地asset下的city.json文件
     *
     * @param context     上下文
     * @return {@link City}
     */
    public City ToCity(Context context){
        try {
            String jsonLocation = AssetJSONFile("city.json", context);
            return new Gson().fromJson(jsonLocation, City.class);
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 读取assets中是string文件
     */
    private static String AssetJSONFile (String filename, Context context) throws IOException {
        AssetManager manager = context.getAssets();
        InputStream file = manager.open(filename);
        byte[] formArray = new byte[file.available()];
        file.read(formArray);
        file.close();
        return new String(formArray);
    }
}
